package com.quocnv.mediascanner;

import java.net.MalformedURLException;
import java.util.ArrayList;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileFilter;

public class SmbFileScanner
{
	public static SmbFileScanner getInstance()
	{
		return new SmbFileScanner();
	}

	public ArrayList<SmbFile> getAll(String path, SmbFileFilter filter)
	{
		SmbFile root;
		ArrayList<SmbFile> smbFiles = null;
		try
		{
			root = new SmbFile(path);
			smbFiles = scanSmbFiles(root, filter);
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
			return null;
		}
		return smbFiles;

	}

	private ArrayList<SmbFile> scanSmbFiles(SmbFile root, SmbFileFilter filter)
	{
		ArrayList<SmbFile> fis = new ArrayList<SmbFile>();
		SmbFile[] files;
		try
		{
			files = root.listFiles();

			for (SmbFile file : files)
			{
				if (file.isFile())
				{
					if (filter == null)
					{
						fis.add(file);
					}
					else if (filter.accept(file))
						fis.add(file);

				}
				else if (file.isDirectory())
				{
					ArrayList<SmbFile> fs = scanSmbFiles(file, filter);
					if (fs != null)
						fis.addAll(fs);
				}
			}
		} catch (SmbException e)
		{
			e.printStackTrace();
			return null;
		}
		return fis;
	}

	public ArrayList<SmbFile> getSmbFiles(String path, SmbFileFilter filter)
			throws SmbException
	{
		SmbFile file;
		ArrayList<SmbFile> files = new ArrayList<SmbFile>();
		try
		{
			file = new SmbFile(path);
			String strParent = file.getParent();
			if (strParent.equals("smb://"))// No parent
			{
				files.add(null);
			}
			else
			{
				SmbFile parentSmbFile = new SmbFile(file.getParent());
				files.add(parentSmbFile);
			}

			for (SmbFile f : file.listFiles())
			{
				if (f.isDirectory())
					files.add(f);

				else if (f.isFile())
				{
					if (filter == null)
					{
						files.add(f);
					}
					else if (filter.accept(f))
						files.add(f);
				}
			}
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
			return null;
		}
		return files;
	}
}
